<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close" :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="登录账号" prop="account">
        <el-input v-model.trim="form.account" autocomplete="off" placeholder="请输入登录账号，初始密码为123456" maxlength="50"></el-input>
      </el-form-item>
      <!-- <el-form-item label="密码" prop="password">
        <el-input v-model.trim="form.password" type="password" autocomplete="off" placeholder="不填默认密码为123456" maxlength="50"></el-input>
      </el-form-item> -->
      <el-form-item label="部门" prop="deptId">
        <treeselect
          v-model="form.deptId"
          :options="options"
          :disable-branch-nodes="false"
          :show-count="true"
          :normalizer="normalizer"
          :flatten-search-results="false"
          noOptionsText="无部门可选"
          placeholder="请选择部门"
        />
      </el-form-item>
      <el-form-item label="工号" prop="userCode">
        <el-input v-model.trim="form.userCode" autocomplete="off" placeholder="请输入用户工号" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="userName">
        <el-input v-model.trim="form.userName" autocomplete="off" placeholder="请输入用户名称" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择" style="width: 100%">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
          <el-option label="未知" value=""></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model.trim="form.phone" autocomplete="off" placeholder="请输入手机号码" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="form.email" autocomplete="off" placeholder="请输入邮箱" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="岗位" prop="postIds">
        <el-select v-model="form.postIds" multiple placeholder="请选择" style="width: 100%">
          <el-option v-for="item in postOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select v-model="form.roleIds" multiple placeholder="请选择" style="width: 100%">
          <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doAdd, doEdit } from '@/api/system/user'
  import { getList } from '@/api/system/dept'
  import { getUserPostList } from '@/api/system/post'
  import { getUserRoleList } from '@/api/system/role'
  import Treeselect from '@riophae/vue-treeselect'
  import { handleTree, handleSelectOption } from '@/utils/index'

  export default {
    name: 'UserEdit',
    components: { Treeselect },

    data() {
      return {
        form: {
          userId: undefined,
          account: undefined,
          userCode: undefined,
          userName: undefined,
          password: undefined,
          email: undefined,
          gender: undefined,
          phone: undefined,
          email: undefined,
          deptId: undefined,
          postIds: [],
          roleIds: [],
        },
        rules: {
          account: [{ required: true, trigger: ['blur', 'change'], message: '请输入登录账号' }],
          deptId: [{ required: true, trigger: ['blur', 'change'], message: '请选择部门' }],
          userCode: [{ required: true, trigger: ['blur', 'change'], message: '请输入用户工号' }],
          userName: [{ required: true, trigger: ['blur', 'change'], message: '请输入用户名称' }],
          password: [{ required: false, trigger: ['blur', 'change'], message: '请输入密码' }],
          gender: [{ required: false, trigger: ['blur', 'change'], message: '请选择性别' }],
          email: [{ required: false, trigger: ['blur', 'change'], message: '请输入正确的邮箱', type: 'email' }],
          phone: [{ required: false, trigger: ['blur', 'change'], message: '请输入手机号码' }],
          postIds: [{ required: true, trigger: ['blur'], message: '请选择岗位' }],
          roleIds: [{ required: true, trigger: ['blur'], message: '请选择角色' }],
        },
        title: '',
        dialogFormVisible: false,
        options: [],
        postOptions: [],
        roleOptions: [],
      }
    },
    created() {},
    methods: {
      async fetchData() {
        let queryForm = { userId: this.form.userId }
        await getList(queryForm).then((res) => {
          if (res.success) {
            this.options = handleTree(res.data, 'deptId', 'parentId', 'children', 0)
          }
        })
        await getUserPostList(queryForm).then((res) => {
          if (res.success) {
            this.postOptions = handleSelectOption(res.data['posts'], 'postName', 'postId')
            this.form.postIds = res.data['postIds']
          }
        })
        await getUserRoleList(queryForm).then((res) => {
          if (res.success) {
            this.roleOptions = handleSelectOption(res.data['roles'], 'roleName', 'roleId')
            this.form.roleIds = res.data['roleIds']
          }
        })
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children,
        }
      },
      showEdit(row) {
        if (!row) {
          this.title = '新增'
        } else {
          this.title = '编辑'
          this.form = Object.assign(this.$options.data().form, row)
        }
        this.fetchData()
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.userId) {
              await doEdit(this.form).then((res) => this.callbackFun(res))
            } else {
              await doAdd(this.form).then((res) => this.callbackFun(res))
            }
          } else {
            return false
          }
        })
      },
      callbackFun(res) {
        if (res.success) {
          this.$baseMessage(res.msg, 'success')
          this.$emit('fetch-data')
          this.close()
        } else {
          this.$baseMessage(res.msg, 'error')
        }
      },
    },
  }
</script>
